package com.google.code.p.restrpc.client.proxy;

import java.util.concurrent.locks.ReentrantLock;

import com.google.code.p.restrpc.RestInvoker;
import com.google.code.p.restrpc.RestInvokerFactory;

/**
 * @author dz
 */
public class CachedRpcInvokerFactory implements RestInvokerFactory {
    
    private ReentrantLock invokerLock = new ReentrantLock();
    
    private RestInvokerFactory restInvokerFactory;
    
    private RestInvoker restInvoker;
    
    /**
     * @param rpcInvokerFactory
     */
    public CachedRpcInvokerFactory(RestInvokerFactory rpcInvokerFactory) {
        super();
        this.restInvokerFactory = rpcInvokerFactory;
    }
    
    /**
     * @return the rpcInvoker
     */
    public RestInvoker getRestInvoker() {
        if (restInvoker != null) {
            return restInvoker;
        }
        
        try {
            invokerLock.lock();
            if (restInvoker != null) {
                return restInvoker;
            }
            restInvoker = restInvokerFactory.getRestInvoker();
        }
        finally {
            invokerLock.unlock();
        }
        
        return restInvoker;
    }
    
    /**
     * @return the rpcInvokerFactory
     */
    public RestInvokerFactory getRestInvokerFactory() {
        return restInvokerFactory;
    }
    
}
